var moment = require('moment');
var colors = require('colors');
var write = require('hy5b/backend/write');
var fs = require('fs');
var lineReader = require('line-reader');

var sh = require('./sh');
var sz = require('./sz');

var service = require('./service');

var util = require('./util');

var controller = require('./controller');

var astock = [];

for (var param in sh) {
    var stock = {
        b: 'sh',
        code: param,
        name: sh[param]
    };
    astock.push(stock);
}

for (var param in sz) {
    var stock = {
        b: 'sz',
        code: param,
        name: sz[param]
    };
    astock.push(stock);
}

var argvs = process.argv;

var resumeBackupFile = 'tmp/resume.stock';

if (argvs[2] != undefined) {
    if (!fs.existsSync(argvs[2])) {
        console.log(argvs[2] + ' is not exist!');
        return;
    }

    controller.setOption({
        resume: true,
        resumeFile: argvs[2],
        resumeBackupFile: resumeBackupFile
    });

    var resumeFs = write(resumeBackupFile, true)
    var resume = {};

    lineReader.eachLine(resumeBackupFile, function(line) {
        var arr = line.split(' ');
        resume[arr[0]] = arr[1];
    }).then(function() {
        util.recursive(function(i, call) {
            if (resume[astock[i].code] == 1) {
                controller.log(true);
                call();
            } else if (resume[astock[i].code] == 2) {
                controller.log();
                call();
            } else
                controller.checkStock(astock[i], function(flag) {
                    resumeFs.write(astock[i].code + (flag ? ' 1' : ' 2') + '\r\n');
                    call();
                });
        }, astock, 0, function() {
            controller.done();
        });
    });
} else {

    controller.setOption({
        resumeBackupFile: resumeBackupFile
    });

    var resumeFs = write(resumeBackupFile);

    util.recursive(function(i, call) {
        controller.checkStock(astock[i], function(flag) {
            resumeFs.write(astock[i].code + (flag ? ' 1' : ' 2') + '\r\n');
            call();
        });
    }, astock, 0, function() {
        controller.done();
    });
}
